package com.miplus.ccrm.report.service.cti;
import me.ihxq.projects.pna.PhoneNumberInfo;
import me.ihxq.projects.pna.PhoneNumberLookup;
import org.springframework.cglib.core.internal.LoadingCache;
import org.springframework.stereotype.Service;

import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.TimeUnit;

/**
 * 电话监控
 */
@Service
public class AspectReportService {

    private final PhoneNumberLookup phoneNumberLookup = new PhoneNumberLookup();

    private final Map<String, String> phoneAreaCache = new ConcurrentHashMap<>(100_000); // 初始容量10万

    /**
     * 获取单个手机号归属地（带缓存）
     */
    public String getPhoneArea(String phone) {
        // 缓存中有则直接返回，没有则查询并缓存
        return phoneAreaCache.computeIfAbsent(phone, this::queryPhoneArea);
    }

    /**
     * 批量获取手机号归属地（带缓存）
     */
    public Map<String, String> getPhoneAreas(Collection<String> phones) {
        Map<String, String> result = new HashMap<>(phones.size());
        for (String phone : phones) {
            // 复用单条查询的缓存逻辑
            result.put(phone, getPhoneArea(phone));
        }
        return result;
    }

    /**
     * 实际查询逻辑（仅在缓存未命中时调用）
     */
    private String queryPhoneArea(String phone) {
        try {
            PhoneNumberInfo found = phoneNumberLookup.lookup(phone).orElseThrow(RuntimeException::new);
            return found.getAttribution().getProvince() + found.getAttribution().getCity();
        } catch (RuntimeException e) {
            return "未知";
        }
    }



//    /**
//     * 获取手机号码归属地
//     *
//     * @param phone 手机号
//     * @return 归属地
//     */
//    public String getPhoneArea(String phone) {
//        PhoneNumberLookup phoneNumberLookup = new PhoneNumberLookup();
//        try {
//            PhoneNumberInfo found = phoneNumberLookup.lookup(phone).orElseThrow(RuntimeException::new);
//            return found.getAttribution().getProvince() + found.getAttribution().getCity();
//        } catch (RuntimeException e) {
//            return "未知";
//        }
//    }


}
